import React, { useState, useContext } from 'react'
import classNames from 'classnames'
import { type MenuItemProps, type SubMenuProps } from './types'
import { MenuContext } from './menu'
import Icon from '../Icon/icon'
// import { CSSTransition } from 'react-transition-group'
import Transition from '../Transition/transition'

export const SubMenu: React.FC<SubMenuProps> = ({
	index,
	title,
	className,
	children
}) => {
	const context = useContext(MenuContext)
	const openedSubMenus = context.defaultOpenSubMenus as Array<string>
	const isOpened =
		index && context.mode === 'vertical' && openedSubMenus.includes(index)

	const [menuOpen, setMenuOpen] = useState(isOpened)
	const classes = classNames('menu-item submenu-item', className, {
		'is-active': context.index === index,
		'is-opened': menuOpen,
		'is-vertical': context.mode === 'vertical'
	})

	const handleClick = (e: React.MouseEvent) => {
		e.preventDefault()
		setMenuOpen(!menuOpen)
	}

	let timer: any
	const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
		clearTimeout(timer)
		e.preventDefault()
		timer = setTimeout(() => {
			setMenuOpen(toggle)
		}, 300)
	}
	const clickEvents =
		context.mode === 'vertical' ? { onClick: handleClick } : {}
	const hoverEvents =
		context.mode !== 'vertical'
			? {
					onMouseEnter: (e: React.MouseEvent) => {
						handleMouse(e, true)
					},
					onMouseLeave: (e: React.MouseEvent) => {
						handleMouse(e, false)
					}
			  }
			: {}

	const renderChildren = () => {
		const subMenuClasses = classNames('v-submenu', {
			'menu-opened': menuOpen
		})
		const childrenComponent = React.Children.map(children, (child, i) => {
			const childElement =
				child as React.FunctionComponentElement<MenuItemProps>
			const { displayName } = childElement.type
			if (displayName === 'MenuItem') {
				return React.cloneElement(childElement, { index: index + '-' + i })
			} else {
				console.error(
					'Warning: Menu as a child which is not a MenuItem component'
				)
			}
		})

		/*
		return 	{ <CSSTransition
			in={menuOpen as boolean}
			timeout={300}
			classNames="zoom-in-top"
			appear
			unmountOnExit
		>
			<ul className={subMenuClasses}>{childrenComponent}</ul>
		</CSSTransition> }
		*/
		return (
			<Transition
				in={menuOpen as boolean}
				timeout={300}
				animation="zoom-in-top"
			>
				<ul className={subMenuClasses}>{childrenComponent}</ul>
			</Transition>
		)
	}

	return (
		<li key={index} className={classes} {...hoverEvents}>
			<div className="submenu-title" {...clickEvents}>
				{title}
				<Icon icon="angle-down" className="arrow-icon" />
			</div>
			{renderChildren()}
		</li>
	)
}

SubMenu.displayName = 'SubMenu'

export default SubMenu
